package com.hdy.javachatroomdemo.Controller;

import com.hdy.javachatroomdemo.Model.*;
import com.hdy.javachatroomdemo.Service.MessageService;
import com.hdy.javachatroomdemo.Service.SessionService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chatRoomSession")
public class SessionController {
    @Autowired
    private SessionService sessionService;
    @Autowired
    private UserProperties userProperties ;
    @Autowired
    private MessageService messageService ;
    @RequestMapping("/sessionList")
    public List<MessageSession> sessionList(HttpServletRequest req){
        List<MessageSession> messageSessionList=new ArrayList<>();
        //1.拿到UserId
        HttpSession session = req.getSession(false);
        if(session == null){
            System.out.println("[SessionController:sessionList]:session对象 is null");
            return messageSessionList;
        }
        User user= (User)session.getAttribute(userProperties.getSession().getKey());
        if(user == null){
            System.out.println("[SessionController:sessionList]User对象 is null");
            return messageSessionList;
        }

        //2.通过userId拿到sessionId 里面的逻辑判断在Service层处理
        List<Integer> SessionIdList = sessionService.getSessionByUserId(user.getUserId());

        //3.通过sessionId拿到好友列表
        for (int sessionId : SessionIdList) {
            //准备好返回对象
            MessageSession messageSession = new MessageSession();
            List<Friend>friends =sessionService.getFriendBySessionId(sessionId,user.getUserId());
            //组装MessageSession并返回
            messageSession.setFriends(friends);
            messageSession.setSessionId(sessionId);

            //这里改成从数据库中获取最后一条消息
            String lastMessage= messageService.queryLastMassage(sessionId);
            messageSession.setLastMassage(lastMessage);
            messageSessionList.add(messageSession);
        }
        //如果一个会话对象都没有,则手动添加一个空的会话对象,用于前端判断
        if(messageSessionList.isEmpty()){
            messageSessionList.add(new MessageSession());
        }
        return messageSessionList;
    }
    @RequestMapping("/createSession")
    //由于前面已经多次判断session和user为空的情况,此处就不判断了,直接简写
    public Map<String,Integer> createSession(Integer friendId, @SessionAttribute("USER_SESSION") User user){
        //交给service层处理插入session
        Map<String,Integer> map=sessionService.addSession(friendId,user.getUserId());
        System.out.println(map);
        return map;
    }
}
